package com.rd.student.ruanjian.class3.gaochenxi.LianXi3.NumberTwo;

public class AddHeTwo {

      public static void main(String[] args) {
            //让构造器中的a和b发生变化,
            for (int i = 0; i < 10; i++) {
                  AddElement add = new AddElement(i * 10 + 1, i * 10 + 10);
                  /*
                        1-10
                        11-20
                        21-30
                        31-40
                        41-50
                        51-60
                        61-70
                        71-80
                        81-90
                        91-100
                   */
                  add.start();
            }
            try {
                  Thread.sleep(1000);
            } catch (InterruptedException e) {
                  throw new RuntimeException(e);
            }
            System.out.println("所有数相加的总和为:" + AddElement.sum);
      }
}

class AddElement extends Thread {

      Object obj = new Object();
      int a;//比较小的数
      int b;//比较大的数

      int tmp = 0;//暂存每一段数的和的
      static int sum = 0;//算所有数总和的

      public AddElement(int a, int b) {
            this.a = a;
            this.b = b;
      }

      @Override
      public void run() {
            synchronized (obj) {
                  for (int i = a; i <= b; i++) {
                        tmp += i;//暂存每一段的和
                  }
                  System.out.println(Thread.currentThread().getName() + " " + tmp);
                  sum += tmp;//总和再继续变化
            }
      }
}
